<template>
    <div class="order-detail-container">
      <div class="page-header">
        <div class="header-left">
          <!-- <el-icon class="back-icon" @click="goBack"><ArrowLeft /></el-icon> -->
          <span class="detail-title">订单详情: {{ orderData.id }}</span>
        </div>
        <el-button @click="goBack" class="return-btn">返回</el-button>
      </div>
      
      <div class="detail-content">
        <!-- 订单状态 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>订单状态</span>
              <div class="header-action">
                <el-button
                  v-if="orderData.status === '待发货'"
                  type="primary"
                  size="small"
                  @click="handleShipment"
                >
                  发货处理
                </el-button>
                
                <el-button
                  v-if="orderData.status === '待付款'"
                  type="danger"
                  size="small"
                  @click="handleCancel"
                >
                  取消订单
                </el-button>
              </div>
            </div>
          </template>
          
          <el-steps :active="getStatusStep(orderData.status)" finish-status="success" simple>
            <el-step title="下单" description="等待买家付款" />
            <el-step title="付款" description="等待卖家发货" />
            <el-step title="发货" description="等待买家收货" />
            <el-step title="完成" description="交易完成" />
          </el-steps>
          
          <div class="order-info">
            <div class="info-item">
              <span class="info-label">当前状态:</span>
              <el-tag :type="getStatusType(getStatusText(orderData.status))">{{ getStatusText(orderData.status) }}</el-tag>
            </div>
            
            <div class="info-item">
              <span class="info-label">订单号:</span>
              <span>{{ orderData.id }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">下单时间:</span>
              <span>{{ orderData.createTime }}</span>
            </div>
            
            <div class="info-item" v-if="orderData.payment_method">
              <span class="info-label">支付方式:</span>
              <span>{{ getPaymentMethodText(orderData.payment_method) }}</span>
            </div>
            
            <div class="info-item" v-if="orderData.payTime">
              <span class="info-label">支付时间:</span>
              <span>{{ orderData.payTime }}</span>
            </div>
            
            <div class="info-item" v-if="orderData.shipTime">
              <span class="info-label">发货时间:</span>
              <span>{{ orderData.shipTime }}</span>
            </div>
            
            <div class="info-item" v-if="orderData.completeTime">
              <span class="info-label">完成时间:</span>
              <span>{{ orderData.completeTime }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 物流信息 -->
        <el-card class="box-card mb-20" v-if="orderData.status === '已发货' || orderData.status === '已完成'">
          <template #header>
            <div class="card-header">
              <span>物流信息</span>
            </div>
          </template>
          
          <div class="logistics-info">
            <div class="info-item">
              <span class="info-label">物流公司:</span>
              <span>{{ orderData.logistics?.company }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">物流单号:</span>
              <span>{{ orderData.logistics?.trackingNumber }}</span>
              <el-button link type="primary" @click="copyTrackingNumber">复制</el-button>
            </div>
            
            <el-timeline v-if="orderData.logistics?.tracking?.length">
              <el-timeline-item
                v-for="(activity, index) in orderData.logistics.tracking"
                :key="index"
                :timestamp="activity.time"
              >
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
        
        <!-- 商品信息 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>商品信息</span>
            </div>
          </template>
          
          <el-table :data="orderData.items" border style="width: 100%">
            <el-table-column label="商品图片" width="100">
              <template #default="scope">
                <el-image
                  :src="getImageUrl(scope.row.image)"
                  :preview-src-list="[getImageUrl(scope.row.image)]"
                  fit="cover"
                  style="width: 80px; height: 80px"
                />
              </template>
            </el-table-column>
            
            <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
            
            <el-table-column prop="price" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.price.toFixed(2) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="quantity" label="数量" width="80" />
            
            <el-table-column label="小计" width="120">
              <template #default="scope">
                ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
          
          <div class="order-summary">
            <div class="summary-item">
              <span>商品总价:</span>
              <span>¥{{ (orderData.itemsTotal || 0).toFixed(2) }}</span>
            </div>
            
            <div class="summary-item">
              <span>运费:</span>
              <span>¥{{ (orderData.shippingFee || 0).toFixed(2) }}</span>
            </div>
            
            <div class="summary-item" v-if="orderData.discount">
              <span>优惠:</span>
              <span>-¥{{ (parseFloat(orderData.discount) || 0).toFixed(2) }}</span>
            </div>
            
            <div class="summary-item total">
              <span>实付金额:</span>
              <span class="price">¥{{ (orderData.amount || 0).toFixed(2) }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 用户与收货信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span>用户信息</span>
                </div>
              </template>
              
              <div class="user-info">
                <div class="info-item">
                  <span class="info-label">用户名:</span>
                  <span>{{ orderData.user?.username }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">用户ID:</span>
                  <span>{{ orderData.user?.id }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">手机号:</span>
                  <span>{{ orderData.user?.phone }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">Email:</span>
                  <span>{{ orderData.user?.email }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">用户注册时间:</span>
                  <span>{{ orderData.user?.registerTime }}</span>
                </div>
                
                <div class="info-item actions">
                  <el-button type="primary" size="small" @click="viewUser">查看用户详情</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span>收货信息</span>
                </div>
              </template>
              
              <div class="shipping-info">
                <div class="info-item">
                  <span class="info-label">收货人:</span>
                  <span>{{ orderData.shipping?.name }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">联系电话:</span>
                  <span>{{ orderData.shipping?.phone }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">收货地址:</span>
                  <span>{{ orderData.shipping?.address }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">邮政编码:</span>
                  <span>{{ orderData.shipping?.postalCode }}</span>
                </div>
                
                <div class="info-item">
                  <span class="info-label">备注:</span>
                  <span>{{ orderData.shipping?.remark || '无' }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 发货弹窗 -->
      <el-dialog
        v-model="shipDialogVisible"
        title="订单发货"
        width="500px"
      >
        <el-form :model="shipForm" label-width="100px">
          <el-form-item label="物流公司">
            <el-select v-model="shipForm.company" placeholder="请选择物流公司" style="width: 100%">
              <el-option label="顺丰速运" value="顺丰速运" />
              <el-option label="中通快递" value="中通快递" />
              <el-option label="圆通速递" value="圆通速递" />
              <el-option label="韵达快递" value="韵达快递" />
              <el-option label="申通快递" value="申通快递" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="快递单号">
            <el-input v-model="shipForm.trackingNumber" placeholder="请输入快递单号" />
          </el-form-item>
          
          <el-form-item label="发货备注">
            <el-input
              v-model="shipForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（选填）"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="shipDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmShip" :loading="submitting">确认发货</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowLeft } from '@element-plus/icons-vue'
  import { getOrderDetail, updateOrderStatus } from '../../api/order'
  
  const route = useRoute()
  const router = useRouter()
  const shipDialogVisible = ref(false)
  const submitting = ref(false)
  const loading = ref(false)
  
  // 发货表单
  const shipForm = reactive({
    company: '',
    trackingNumber: '',
    remark: ''
  })
  
  // 订单状态对应的进度步骤
  const getStatusStep = (status) => {
    const statusMap = {
      // 中文状态
      '待付款': 0,
      '待发货': 1,
      '已发货': 2,
      '已完成': 3,
      '已取消': 0,
      '已退款': 0,
      // 英文状态
      'pending': 0,
      'paid': 1,
      'shipped': 2,
      'completed': 3,
      'cancelled': 0,
      'refunded': 0
    }
    return statusMap[status] || 0
  }
  
  // 订单状态对应的标签类型
  const getStatusType = (status) => {
    const typeMap = {
      // 中文状态
      '待付款': 'warning',
      '待发货': 'info',
      '已发货': 'primary',
      '已完成': 'success',
      '已取消': 'danger',
      '已退款': 'danger',
      // 英文状态
      'pending': 'warning',
      'paid': 'info',
      'shipped': 'primary',
      'completed': 'success',
      'cancelled': 'danger',
      'refunded': 'danger'
    }
    return typeMap[status] || 'info'
  }
  
  // 订单数据
  const orderData = reactive({
    id: '',
    status: '',
    createTime: '',
    payTime: '',
    shipTime: null,
    completeTime: null,
    logistics: null,
    items: [],
    itemsTotal: 0,
    shippingFee: 0,
    discount: 0,
    amount: 0,
    user: {
      id: '',
      username: '',
      phone: '',
      email: '',
      registerTime: ''
    },
    shipping: {
      name: '',
      phone: '',
      address: '',
      postalCode: '',
      remark: ''
    }
  })
  
  // 获取订单详情
  const fetchOrderDetail = async (id) => {
    loading.value = true
    try {
      const data = await getOrderDetail(id)
      
      // 确保金额字段为数字类型
      data.itemsTotal = parseFloat(data.itemsTotal || 0)
      data.shippingFee = parseFloat(data.shippingFee || 0)
      data.discount = parseFloat(data.discount || 0)
      data.amount = parseFloat(data.total_amount || data.amount || 0)
      
      // 处理订单项的价格字段
      if (data.items && data.items.length > 0) {
        data.items = data.items.map(item => ({
          ...item,
          price: parseFloat(item.price || 0)
        }))
      }
      
      Object.assign(orderData, data)
    } catch (error) {
      ElMessage.error('获取订单详情失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 返回上一页
  const goBack = () => {
    router.back()
  }
  
  // 复制快递单号
  const copyTrackingNumber = () => {
    if (orderData.logistics?.trackingNumber) {
      navigator.clipboard.writeText(orderData.logistics.trackingNumber)
        .then(() => ElMessage.success('快递单号已复制'))
        .catch(() => ElMessage.error('复制失败，请手动复制'))
    }
  }
  
  // 查看用户详情
  const viewUser = () => {
    if (orderData.user && orderData.user.id) {
      router.push(`/users/${orderData.user.id}`)
    } else {
      ElMessage.warning('用户ID不存在')
    }
  }
  
  // 发货处理
  const handleShipment = () => {
    shipDialogVisible.value = true
    // 重置表单
    shipForm.company = ''
    shipForm.trackingNumber = ''
    shipForm.remark = ''
  }
  
  // 确认发货
  const confirmShip = async () => {
    if (!shipForm.company) {
      ElMessage.warning('请选择物流公司')
      return
    }
    
    if (!shipForm.trackingNumber) {
      ElMessage.warning('请输入快递单号')
      return
    }
    
    submitting.value = true
    
    try {
      await updateOrderStatus(orderData.id, {
        status: '已发货',
        logisticsCompany: shipForm.company,
        trackingNumber: shipForm.trackingNumber,
        shippingRemark: shipForm.remark
      })
      
      ElMessage.success('发货成功')
      shipDialogVisible.value = false
      fetchOrderDetail(orderData.id)
    } catch (error) {
      ElMessage.error('发货失败: ' + error.message)
    } finally {
      submitting.value = false
    }
  }
  
  // 取消订单
  const handleCancel = () => {
    ElMessageBox.confirm(`确定要取消订单 ${orderData.id} 吗?`, '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await updateOrderStatus(orderData.id, { status: '已取消' })
        ElMessage.success('订单已取消')
        fetchOrderDetail(orderData.id)
      } catch (error) {
        ElMessage.error('取消订单失败: ' + error.message)
      }
    }).catch(() => {})
  }
  
  // 添加处理图片URL的函数
  const getImageUrl = (image) => {
    if (!image) return '';
    
    // 检查是否已经是完整的URL
    if (image.startsWith('http')) return image;
    
    // 服务器基础URL
    const serverBaseUrl = 'http://localhost:5000';
    
    // 确保路径包含uploads
    if (image.startsWith('/uploads/')) {
      return `${serverBaseUrl}${image}`;
    } else if (image.startsWith('/')) {
      return `${serverBaseUrl}/uploads${image}`;
    } else {
      return `${serverBaseUrl}/uploads/${image}`;
    }
  }
  
  // 支付方式中文显示的转换函数
  const getPaymentMethodText = (method) => {
    const paymentMethods = {
      'alipay': '支付宝',
      'wechat': '微信支付'
    }
    return paymentMethods[method] || method;
  }
  
  // 添加订单状态的英文到中文的转换函数
  const getStatusText = (status) => {
    const statusText = {
      '待付款': '待付款',
      '待发货': '待发货',
      '已发货': '已发货',
      '已完成': '已完成',
      '已取消': '已取消',
      '已退款': '已退款',
      'pending': '待付款',
      'paid': '待发货',
      'shipped': '已发货',
      'completed': '已完成',
      'cancelled': '已取消',
      'refunded': '已退款'
    }
    return statusText[status] || status;
  }
  
  onMounted(() => {
    const orderId = route.params.id
    fetchOrderDetail(orderId)
  })
  </script>
  
  <style scoped>
  .order-detail-container {
    padding: 20px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header-left {
    display: flex;
    align-items: center;
  }
  
  .back-icon {
    font-size: 16px;
    margin-right: 8px;
    cursor: pointer;
  }
  
  .detail-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }
  
  .return-btn {
    margin-left: auto;
  }
  
  .detail-content {
    margin-top: 20px;
  }
  
  .mb-20 {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .header-action {
    display: flex;
    gap: 10px;
  }
  
  .order-info,
  .logistics-info,
  .user-info,
  .shipping-info {
    padding: 15px;
  }
  
  .info-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
  }
  
  .info-item:last-child {
    margin-bottom: 0;
  }
  
  .info-label {
    font-weight: bold;
    margin-right: 10px;
    width: 100px;
    display: inline-block;
  }
  
  .actions {
    margin-top: 20px;
  }
  
  .order-summary {
    margin-top: 20px;
    padding: 15px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }
  
  .summary-item {
    margin-bottom: 10px;
    display: flex;
    gap: 20px;
  }
  
  .summary-item.total {
    margin-top: 10px;
    font-weight: bold;
    font-size: 16px;
  }
  
  .price {
    color: #f56c6c;
  }
  
  .box-card {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  </style>